<?php
namespace Admin\Controller;
use Think\Controller;
class AdminbaseController extends Controller {
	
	public $curUser;
	
	function _initialize() {
		$userService = new \Users\Service\UsersService();
		
		if(!$userService->isLogin()){
			//redirect(U('Admin/Public/login'));
			$url = '/users/login?next='.urlencode('/admin.html');
			header("location:".$url);
			exit();
		}
		$this->curUser = $userService->getCurrentUser();  //获取当前登录用户
		//dump($this->curUser);
		//如果该用户没有管理员权限，则返回首页
// 		if(!strpos($this->curUser['role'],'_ADMIN')){
// 			header("location:/");
// 			exit();
// 		}



		$this->_get_auth($this->curUser['role']);
	}
	
	public function _get_auth($role){
		//获取当前用户权限
		if(!$_SESSION['curUserRole']){
			$map['title'] = $role;
			$_SESSION['curUserRole'] = M('AuthGroup')->where($map)->find();
		}
		if($role == 'teacher'){
			//$auths = \Users\Controller\AuthadminController::_get_file_auths('adminTeacher'); //获取adminTeacher分组下的权限
			$this->leftmenu = 'adminTeacher';
		}elseif (strpos($role,'XIAOQU_ADMIN') || strpos($role,'XIAOWU_ADMIN') || strpos($role,'ZHUREN_ADMIN')){
			$this->leftmenu = 'adminLeft';
			$this->showrules = explode(',',$_SESSION['curUserRole']['rules']);
		}else{
			$this->leftmenu = 'adminLeft';
			
			//无需验证配置
			$not_check = array(
					'/admin/index/index',
					'/admin/index/welcome',
					'/users/authadmin/error'
			);
			if(!in_array( strtolower('/'.MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME), $not_check)){
				$auths = \Users\Controller\AuthadminController::_get_file_auths('adminLeft'); //获取admin分组下的权限
// 				dump($auths);
				$cur_auth = $auths[strtolower(MODULE_NAME)][strtolower(CONTROLLER_NAME )][strtolower(ACTION_NAME)];
					
				//判断是否为超级管理员
				if($this->curUser['role'] !== 'ROLE_SUPER_ADMIN'){
					
					$rules = explode(',', $_SESSION['curUserRole']['rules']);
// 					dump($cur_auth);
// 					dump($rules);
// 					exit();
					if(!in_array($cur_auth,$rules)){
							
						if(strpos(ACTION_NAME,'del') !== FALSE || strpos(ACTION_NAME,'status') !== FALSE || strpos(ACTION_NAME,'check') !== FALSE){
							$this->error('你没有权限进行该操作');
						}else{
							redirect(U('users/authadmin/error'));
						}
							
						exit();
						//$this->error('You do not have this authority',U('users/authadmin/error'));
					}
				}
			}
			
		}
	}
	
	/**
	 *  排序 排序字段为listorders数组 POST 排序字段为：listorder
	 */
	protected function _listorders($model) {
		if (!is_object($model)) {
			return false;
		}
		$pk = $model->getPk(); //获取主键名称
		$ids = $_POST['listorders'];
		foreach ($ids as $key => $r) {
			$data['listorder'] = $r;
			$model->where(array($pk => $key))->save($data);
		}
		return true;
	}
}